import * as THREE from 'three'
import { KongZhi } from './KongZhi.js'
import { yeMianZhuanXiangJiZuoBiao } from '../gongJu/gongJu.js'
import { huanJing } from '../huanJing/HuanJing.js'
import { XinXiKuang } from '../gongJu/gongJu.js'
import { FaGuangTi } from '../changJing/wuTi/FaGuangTi.js'

// 物体的指针经过事件的目标
let wuTiMuBiao = {
	qianMuBiao: null, // 前一个物体对象
	muBiao: null, // 事件目标物体对象
}

let wuTiMuBiaoDaiLi = new Proxy(wuTiMuBiao, {
	set: (duiXiang, jian, zhi) => {
		if (jian == 'muBiao' && duiXiang['muBiao'] != zhi) {
			duiXiang['qianMuBiao'] = duiXiang[jian]
			duiXiang['muBiao'] = zhi
			duiXiang['muBiao']?.chuFaShiJian({ leiXing: 'zhiZhenJingGuo' })
			duiXiang['qianMuBiao']?.chuFaShiJian({ leiXing: 'zhiZhenLiKai' })
		}
		return true
	},
	get(duiXiang, jian) { // get: function () {}
		return Reflect.get(...arguments)
	}
})

let xinXiKuang = new XinXiKuang()

export class ShuBiaoShiJian extends KongZhi {
	constructor() {
		super()
		
	}
	
	chuLi(shiJian) {
		// if (shiJian.type == 'pointermove') this.zhiZhenJingGuoHanShu(shiJian)
		if (shiJian.type == 'pointerdown') this.paoWu(shiJian)
	}
	// 指针经过函数
	zhiZhenJingGuoHanShu(shiJian) {
		// 射线检测有性能问题
		if (document.pointerLockElement != null) return
		
		let zuoBiao = new THREE.Vector2(...yeMianZhuanXiangJiZuoBiao(shiJian.offsetX, shiJian.offsetY))
		let raycaster = new THREE.Raycaster()
		raycaster.setFromCamera( zuoBiao, huanJing.camera )
		
		let jianCeMoXing = []
		huanJing.scene.traverseVisible(a => {
			if (a.isMesh && !a.isSprite) jianCeMoXing.push(a)
		})
		
		const intersects = raycaster.intersectObjects( jianCeMoXing, false )
		if ( intersects.length > 0 ) {
			for (let i = 0, il = intersects.length; i < il; i++) {
				let intersect = intersects[i]
				let wuTi = intersect.object.userData.huoQuWuTi?.()
				if (wuTi) {
					wuTiMuBiaoDaiLi.muBiao = wuTi
					xinXiKuang.xianShi(wuTi.mingZi, intersect.point)
					break
				}
				if (intersect.instanceId) {
					xinXiKuang.xianShi('行星系统' + intersect.instanceId, intersect.point)
					break
				}
			}
		} else {
			xinXiKuang.yinCang()
			wuTiMuBiaoDaiLi.muBiao = null
		}
	}
	// 抛物测试
	paoWu(shiJian) {
		if (shiJian.button == 2) {
			let d = new THREE.Vector3()
			huanJing.camera.getWorldDirection(d)
			
			const geometry = new THREE.BoxGeometry( 0.5, 0.5, 0.5 );
			const material = new THREE.MeshStandardMaterial({ color: '#0af' })
			const box = new THREE.Mesh( geometry, material )
			let pengZhuang = box.clone()
			pengZhuang.userData.xingZhuang = '方体'
			huanJing.camera.getWorldPosition(box.position)
			let j = new FaGuangTi(box, pengZhuang, 1)
			j.mingZi = 'abc'
			j.jiaZai()
			j.sheZhiPengZhuangTi({ xianSuDu: d.multiplyScalar(5) })
			// j.faGuang(0xffffff, 3, 0)
		}
	}
}